<?php

namespace app\admin\controller;

use app\admin\model\AdminPermission;
use app\admin\model\AdminRole;
use Exception;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use support\Request;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class Admin_role extends Base
{

    /**
     * 角色
     * @param  Request  $request
     * @return string|Response
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $list = $this->model->order('id', 'desc')->select();
            return json(['msg'    => '', 'code' => 0, 'data' => $list->toArray(),
                         'extend' => ['count' => $list->count()],
            ]);
        }
        return view('admin_role/index');
    }

    /**
     * 添加
     * @param  Request  $request
     * @return string|Response
     * @throws Exception
     */
    public function add(Request $request)
    {
        if ($request->isAjax()) {
            $data = $request->post();
            //验证
            try {
                v::input($request->post(), [
                    'name' => v::alnum()->length(1, 64)->setName('名称'),
                ]);
                if ($this->model->where(['name' => $request->post('name')])->find()) {
                    throw new Exception('名称已存在');
                }
            } catch (ValidationException $e) {
                return json(['code' => 201, 'msg' => '添加失败', 'data' => $e->getMessage()]);
            }

            try {
                $this->model->create($data);
            } catch (Exception $e) {
                return json(['code' => 201, 'msg' => '添加失败', 'data' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '添加成功']);
        }
        return view('admin_role/add');
    }

    /**
     * 编辑
     * @param  Request  $request
     * @return string|Response
     * @throws Exception
     */
    public function edit(Request $request)
    {
        $id = $request->input('id');
        $model = $this->model->find($id);
        if ($request->isAjax()) {
            $data = $request->post();
            $data['id'] = $model['id'];
            //验证
            try {
                v::input($request->post(), [
                    'name' => v::alnum()->length(1, 64)->setName('名称'),
                ]);
                if ($this->model->where(['name' => $request->post('name')])->find()) {
                    throw new Exception('名称已存在');
                }
            } catch (ValidationException $e) {
                return json(['code' => 201, 'msg' => $e->getMessage()]);
            }
            try {
                $model->save($data);
            } catch (Exception $e) {
                return json(['code' => 201, 'msg' => '更新失败', 'data' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '更新成功']);
        }
        return view('admin_role/edit', [
            'model' => $model,
        ]);
    }

    /**
     * 删除
     * @param  Request  $request
     */
    public function del(Request $request)
    {
        return json(['code' => 201, 'msg' => '演示禁止删除']);
        $id = $request->input('id');
        $model = $this->model->find($id);
        if ($model->isEmpty()) {
            return json(['code' => 201, 'msg' => '数据不存在']);
        }
        if ($id == 1) {
            return json(['msg' => '超级管理员无法删除', 'code' => '201']);
        }
        try {
            $model->delete();
            Db::table('admin_admin_role')->where('role_id', $id)->delete();
        } catch (Exception $e) {
            return json(['code' => 201, 'msg' => '删除失败', 'data' => $e->getMessage()]);
        }
        return json(['code' => 200, 'msg' => '删除成功']);
    }

    /**
     * 用户分配角色
     * @param  Request  $request
     * @return
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function permission(Request $request)
    {
        $id = $request->input('id');
        $role = $this->model->find($id);
        $permissions = AdminPermission::order('sort', 'asc')->select();
        foreach ($permissions as $permission) {
            if ($role['permissions']) {
                foreach (explode(',', $role['permissions']) as $p) {
                    if ($permission->id == $p) {
                        $permission->own = true;
                    }
                }
            }
        }
        $permissions = get_tree($permissions->toArray());
        if ($request->isAjax()) {
            $postPermissions = $request->post('permissions') ?? '';
            if (!$postPermissions) {
                return json(['code' => 201, 'msg' => '至少选择一项']);
            }
            try {
                $role->permissions = implode(",", $postPermissions);
                $role->save();
            } catch (Exception $e) {
                return json(['code' => 201, 'msg' => '更新失败', 'data' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '更新成功']);
        }
        return view('admin_role/permission', [
            'permissions' => $permissions,
            'role'        => $role,
        ]);
    }

    /**
     * 回收站
     */
    public function recycle(Request $request)
    {
        if ($request->isAjax()) {
            if ($request->method() == 'POST') {
                $ids = $request->input('ids');
                if (!is_array($ids)) {
                    return json(['msg' => '参数错误', 'code' => '201']);
                }
                $msg = '恢复';
                try {
                    if ($request->input('type') == '1') {
                        $data = $this->model->onlyTrashed()->whereIn('id', $ids)->select();
                        foreach ($data as $k) {
                            $k->restore();
                        }
                    } else {
                        if (in_array(1, $ids)) {
                            return json(['msg' => '超级管理员无法删除', 'code' => '201']);
                        }
                        $msg = '删除';
                        $this->model->destroy($ids, true);
                    }
                } catch (Exception $e) {
                    return json(['msg' => $msg.'失败', 'code' => '201', 'data' => $e->getMessage()]);
                }
                return json(['msg' => $msg.'成功', 'code' => '200']);
            }
            $list = $this->model->onlyTrashed()->order('id',
                'desc')->withoutField('delete_time')->where($this->where)->paginate($request->input('limit'));
            $data = [
                'msg'   => '',
                'data'  => $list->items(),
                'code'  => 0,
                'count' => $list->total(),
                'limit' => $request->get('limit'),
            ];
            return json($data);
        }
        return view('admin_role/recycle');
    }

    protected function initialize()
    {
        $this->model = new AdminRole;
    }
}
